# -*- coding:UTF-8 -*-
import rpyc
from rpyc import Service
from rpyc.utils.server import ThreadedServer

from fileCore.filemgmt import upload_file, write_docker_file, get_yaml_info
from dockerCore.dockermgmt import stop_docker, rm_docker, rmi_docker, restart_docker, run_docker
from nginxCore.nginxmgmt import operate_nginx
from domianCore.domainmgmt import add_domain, del_domain
from utils.config import RPCIP, RPCPORT

rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True
rpyc.core.protocol.DEFAULT_CONFIG['sync_request_timeout'] = 60


class AiApiCoreClass(Service):
    docker_dict = {}
    def on_connect(self, conn):
        print(f"客户端连接: {conn}")

    def on_disconnect(self, conn):
        print(f"客户端断开链接: {conn}")

    def exposed_upload_file(self, filename, content, apps_path="AppsTmp", is_save=True):
        """上传ZIP文件到CORE服务，用于Docker部署

        Args:
            filename (_type_): _description_
            content (_type_): _description_
            apps_path (str, optional): _description_. Defaults to "AppsTmp".
            is_save (bool, optional): _description_. Defaults to True.

        Returns:
            _type_: _description_
        """
        return upload_file(filename, content, apps_path, is_save)

    def exposed_write_docker_file(self, filename, run_main):
        """把template/template_docker_base 写入到应用中，做为Dockerfile

        Args:
            filename (_type_): _description_
            run_main (_type_): _description_

        Returns:
            _type_: _description_
        """
        return write_docker_file(filename, run_main)

    def exposed_get_yaml_info(self, filename, app_path="AppsTmp"):
        """获取应用的yaml内容

        Args:
            filename (_type_): _description_
            app_path (str, optional): _description_. Defaults to "AppsTmp".

        Returns:
            _type_: _description_
        """
        return get_yaml_info(filename, app_path)

    def exposed_operate_nginx(self, mode, nginx_name, server_name, ip, port):
        """创建一个vhost的nginx.conf，并且重载nginx

        Args:
            mode (_type_): _description_
            nginx_name (_type_): _description_
            server_name (_type_): _description_
            ip (_type_): _description_
            port (_type_): _description_

        Returns:
            _type_: _description_
        """
        return operate_nginx(mode, nginx_name, server_name, ip, port)

    def exposed_stop_docker(self, host, docker_ip, docker_name, container_id, image_id):
        """停止docker容器

        Args:
            host (_type_): _description_
            docker_ip (_type_): _description_
            docker_name (_type_): _description_
            container_id (_type_): _description_
            image_id (_type_): _description_

        Returns:
            _type_: _description_
        """
        return stop_docker(host, docker_ip, docker_name, container_id, image_id)

    def exposed_rm_docker(self, container_id):
        """删除docker容器

        Args:
            container_id (_type_): _description_

        Returns:
            _type_: _description_
        """
        return rm_docker(container_id)

    def exposed_rmi_docker(self, docker_id, image_name):
        """删除docker images

        Args:
            docker_id (_type_): _description_
            image_name (_type_): _description_

        Returns:
            _type_: _description_
        """
        return rmi_docker(docker_id, image_name)

    def exposed_restart_docker(self, host, docker_ip, docker_name, container_id, image_id):
        """重启容器

        Args:
            host (_type_): _description_
            docker_ip (_type_): _description_
            docker_name (_type_): _description_
            container_id (_type_): _description_
            image_id (_type_): _description_

        Returns:
            _type_: _description_
        """
        return restart_docker(host, docker_ip, docker_name, container_id, image_id)

    def exposed_run_docker(self, filename, umail, app_cn_name="", app_desc="", app_dock="", app_language="", app_main_code_file_path=""
                           ):
        """build一个images并且运行一个容器

        Args:
            filename (_type_): _description_
            umail (_type_): _description_

        Returns:
            _type_: _description_
        """
        tag_name = filename.lower()
        if self.docker_dict.get(tag_name, umail) != umail:
            return False, "应用已有其他用户使用"
        self.docker_dict[tag_name] = umail
        print(self.docker_dict)
        return run_docker(filename, umail, app_cn_name, app_desc, app_dock, app_language, app_main_code_file_path)

    def exposed_add_domain(self, app_name, ip):
        """创建一个域名

        Args:
            app_name (_type_): _description_
            ip (_type_): _description_

        Returns:
            _type_: _description_
        """
        return add_domain(app_name, ip)

    def exposed_search_sub_domain(self, rr):
        pass

    def exposed_set_domain_status(self, RecordId, status=False):
        pass

    def exposed_update_domain(self, RecordId, rr, ip):
        pass

    def exposed_del_domain(self, RecordId):
        """删除一个域名

        Args:
            RecordId (_type_): _description_

        Returns:
            _type_: _description_
        """
        return del_domain(RecordId)

    def exposed_test_connect(self):
        return


if __name__ == '__main__':
    print(
        f"--------------Core RPC服务启动成功--------------\r\nip={RPCIP},port={RPCPORT}")
    # 启动服务
    s = ThreadedServer(AiApiCoreClass, hostname=RPCIP, port=RPCPORT,
                       protocol_config=rpyc.core.protocol.DEFAULT_CONFIG)
    s.start()
